package com.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;

import com.model.Stock;
import com.query.StockQuery;

public class StockDAOImpl extends BaseHibernateDAO<Stock, StockQuery> {

	@Override
	public Class<Stock> getModelClass() {
		return Stock.class;
	}

	@Override
	public List<String> getListNames() {
		List<String> list = new ArrayList<String>();
		list.add("listaMovimientoStock");
		return list;
	}

	@Override
	public Stock findBy(Long id) throws DataAccessException {
		DetachedCriteria criteria = DetachedCriteria.forClass(Stock.class);
		criteria.add(Restrictions.eq("producto.id", id));
		@SuppressWarnings("unchecked")
		List<Stock> object = (List<Stock>) getHibernateTemplate().findByCriteria(criteria);
		if (object!=null && !object.isEmpty()){
			return object.get(0);
		}else{
			return null;
		}
	}


	@Override
	public Stock findBy(Long idCliente, Long idProducto, Long idProveedor) throws DataAccessException {
		Stock stock = super.findBy(idCliente, idProducto, idProveedor);
		return stock;
	}
	
	
	/*
	 * Busca los productos que tienen bajo stock
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Stock> getList(String nombreOID) {

		List<Stock> listaStock = null;

		DetachedCriteria criteria = DetachedCriteria.forClass(Stock.class)
				.createAlias("producto", "producto");

		// si el tiene igual o menos que stock mínimo
		criteria.add(Restrictions.or(
				Restrictions.gtProperty("producto.stockMinimo", "cantidad"),
				Restrictions.eqProperty("producto.stockMinimo", "cantidad")));

		listaStock = (List<Stock>) getHibernateTemplate().findByCriteria(
				criteria);

		return listaStock;
	}

	@Override
	public Stock get(Object query) throws DataAccessException {

		Long depositoID = (Long) query;

		DetachedCriteria criteria = DetachedCriteria.forClass(Stock.class).add(
				Restrictions.eq("deposito.id", depositoID));

		Stock stock = (Stock) getHibernateTemplate().findByCriteria(criteria)
				.get(0);

		return stock;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Stock> getList(Object query) throws DataAccessException {

		StockQuery stockQuery = (StockQuery) query;

		List<Stock> listaStock = null;

		DetachedCriteria criteria = DetachedCriteria.forClass(Stock.class)
				.createAlias("producto", "producto");

		criteria.createAlias("deposito", "deposito");

		criteria.add(Restrictions.and(
				Restrictions.eq("producto.id", stockQuery.getProductoID()),
				Restrictions.eq("deposito.id", stockQuery.getDepositoID())));

		listaStock = (List<Stock>) getHibernateTemplate().findByCriteria(
				criteria);

		return listaStock;

	}

}
